﻿using Corina.Win.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Corina.Enumerations;
using System.ComponentModel.Composition;
using Microsoft.Win32;
using System.IO;
using Corina.Commands;
using System.Windows.Input;
using Corina.Win.Helpers;

namespace Corina.Win.ServerHub.Viewmodels
{
    [Export(typeof(IView))]
    public class RunlogViewmodel : PageViewmodelBase<Corina.Win.ServerHub.App>
    {
        public RunlogViewmodel()
        {
            Title = "运行日志";
            UriString = "RunlogView";
            UriType = UriType.OutApp;
            Icon = "ICON_DOC1";
            DataContext.RunlogChanged += RunlogChanged;
        }

        private void RunlogChanged(object sender, EventArgs e)
        {
            RaisePropertyChanged(() => Content);
            RaisePropertyChanged(() => ExportCommand);
        }

        public string Content
        {
            get
            {
                return DataContext.Runlog.ToString();
            }
        }

        public ICommand CleanCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        DataContext.Runlog.Clear();
                        RaisePropertyChanged(() => Content);
                        RaisePropertyChanged(() => ExportCommand);
                    }
                };
            }
        }

        public ICommand ExportCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(Content); },
                    ExecuteCallback = delegate
                    {
                        Export();
                    }
                };
            }
        }

        private void Export()
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = "txt";
            dialog.FileName = string.Format("server log({0})", DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
            dialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
            dialog.ShowDialog();
            if (!string.IsNullOrEmpty(dialog.FileName))
            {
                FileStream fs = new FileStream(dialog.FileName, FileMode.CreateNew, FileAccess.Write);
                using (StreamWriter writer = new StreamWriter(fs))
                {
                    writer.AutoFlush = true;
                    writer.Write(Content);
                    writer.Close();
                }
            }
        }
    }

}
